<?php


namespace addon\local_upload\event;


class Storage
{

    /**
     * 将临时目录的图片生成缩略图并保存到正式目录
     * @param $param
     * @return string
     */
    public function handle($param): string
    {
        if (isset($param['image'])) {
            $image = str_replace(request()->domain(), '', $param['image']);
            if (is_file('.' . $image) && strpos($image, 'tmp')) {
                $image = \think\Image::open('.' . $image);
                if (!is_dir(public_path() . 'storage/upload/' . $param['type'])) {
                    mkdir(public_path() . 'storage/upload/' . $param['type'], 0777, true);
                }
                $file_name = 'storage/upload/' . $param['type'] . '/' . date('YmdHis') . random_keys(10);
                $big_image = public_path() . $file_name . '-big.jpg';
                $min_image = public_path() . $file_name . '-min.jpg';
                $image->thumb(750, 750)->save($big_image);
                $image->thumb(375, 375)->save($min_image);

                return request()->domain() . '/' . $file_name . '.jpg';
            }
        }
        return $param['image'] ?? '';
    }
}